<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/8/9
 * Time: 15:46
 */

namespace app\index\controller;

use app\index\model\Archives;
use app\index\model\ArchivesCategory;
use app\index\model\Archives_file;
use app\index\model\Arc_extend_info;
use app\index\model\FileLog;
use app\index\model\Interfile;
use app\index\model\Tag;
use app\index\model\TagArchivesRelation;
use app\index\model\User;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class Common extends AdminController {
// class Common {/
	protected $request;
	protected $rootPath;
	protected $folderPath;
	protected $demoPath;
	protected $admin_session;
	protected $_tokenPath;
	protected $cate_id;
	protected $ac_model;
	protected $a_model;
	protected $acf_model;
	protected $aei_model;
	protected $fl_model;
	protected $inf_model;

	public function __construct(Request $request = null) {
		parent::__construct($request);
		session('admin', ['id' => $_SESSION['think']['username'][0]['user_id'], 'name' => $_SESSION['think']['username'][0]['user_name']]);
		$this->request = $request;
		$this->rootPath = $_SERVER['DOCUMENT_ROOT'];
		$this->folderPath = $this->rootPath . '/folder';
		$this->demoPath = $this->rootPath . '/demo';
		$this->_tokenPath = $this->rootPath . '/token';
		$this->admin_session = session('admin');
		$user = new User();
		$this->a_model = new Archives();
		$this->fl_model = new FileLog();
		$this->inf_model = new Interfile();
		$user_data = $user->getListByCondition(array(), 'user_id desc');
		session('user_data', arrayValueToKey($user_data, 'user_id'));

		$this->ac_model = new ArchivesCategory();
		$this->acf_model = new Archives_file();
		$this->aei_model = new Arc_extend_info();
	}

	//文件自动创建
	public function autoCreate($filetype, $cate_type = 1) {
		if ($this->request->instance()->isPost()) {
			$cate_id = session('cate_id') ? session('cate_id') : 0;
			if (in_array($cate_id, array('-1', '-2', '-3', '-4'))) {
				$cate_id = 0;
			}
			$ac_model = new ArchivesCategory();
			$name = $this->request->post('name', '');
			$describe = $this->request->post('describe', '');
			$title = $this->request->post('title', '');
			if (!empty($cate_id)) {
				$p_data = $ac_model->where(array('cate_id' => $cate_id, 'cate_type' => $cate_type))->find();
				$bid = $p_data['create_org_id'];
				if (empty($p_data)) {
					jsonOut(0, '上级目录错误');
				}
				// if ($p_data['cate_parent_id'] != 0) {
				// 	$p_datas = arrayValueToKey($ac_model->where(array('cate_type' => $cate_type))->select(), 'cate_id');
				// 	$p_path = trim(getAncestors($p_datas, $cate_id, 0), ',');
				// 	$p_path = explode(',', $p_path);
				// 	foreach ($p_path as $k => $v) {
				// 		$p = explode('-', $v);
				// 		$p_path[$k] = $p[1];
				// 	}
				// 	$p_path = array_reverse($p_path, true);
				// 	if ($bid == '0') {
				// 		$path = $this->folderPath . '/' . $cate_type . '/' . implode('/', $p_path) . '/';
				// 	} else {
				// 		$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . implode('/', $p_path) . '/';
				// 	}

				// } else {
				// 	if ($bid == '0') {
				// 		$path = $this->folderPath . '/' . $cate_type . '/' . $p_data['cate_name'] . '/';
				// 	} else {
				// 		$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . $p_data['cate_name'] . '/';
				// 	}

				// }
			} else {
				//多部门 文件创建  以 部门ID+文件名的形式
				if ($_SESSION['think']['username'][0]['user_name'] != 'admin') {
					$uid = $_SESSION['think']['username'][0]['user_id'];
					$bid = $this->getOrgIdByUid($uid);
					$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/';
				} else {
					$path = $this->folderPath . '/' . $cate_type . '/';
				}
			}

			switch ($filetype) {
			case 'folder':
				if (empty($name)) {
					jsonOut(0, '文件夹名称不能为空');
				}
				$num = $this->ac_model->where('cate_parent_id', $cate_id)->where('cate_name', $name)->where('cate_type', $cate_type)->count();
				if ($num != 0) {
					jsonOut(0, '目录已存在');
				}
				// if (is_dir($path . '/' . $name)) {
				// 	jsonOut(0, '目录已存在');
				// }

				// if (mkdir($path . '/' . $name, 0777, true)) {
				$save_data = [
					'cate_parent_id' => $cate_id,
					'cate_name' => $name,
					'cate_desc' => $describe,
					'cate_type' => $cate_type,
					'create_user_id' => $this->admin_session['id'],
					'create_time' => date('Y-m-d H:i:s'),
					'create_org_id' => empty($bid) ? 0 : $bid,
				];
				if ($ac_model->insert($save_data)) {
					$id = $ac_model->getLastInsID();
					$this->tableBak('archives', 'archives_version', 'arc_id', 'original_id', $id, 'backup_reasons', '创建');
					jsonOut(1, '创建成功');
				} else {
					jsonOut(0, '创建失败');
				}
				// } else {
				// 	jsonOut(0, '创建失败');
				// }
				break;
			case 'word':
				if (empty($cate_id)) {
					jsonOut(0, '请先选择目录后在操作');
				}

				if (empty($name)) {
					jsonOut(0, '文件名称部能为空');
				}
				if (is_file($path . $name . '.docx')) {
					jsonOut(0, 'Word文件已经存在');
				}

				$cp = copy($this->demoPath . '/demo.docx', $path . $name . '.docx');
				if ($cp) {
					$save_data = array(
						'arc_title' => $title,
						'arc_name' => $name,
						'arc_desc' => $describe,
						'category_id' => $cate_id,
						'create_user_id' => $this->admin_session['id'],
						'create_time' => date('Y-m-d H:i:s'),
						'arc_type' => 'docx',
						'update_user_id' => $this->admin_session['id'],
						'update_time' => date('Y-m-d H:i:s'),
						'arc_file_size' => filesize($this->demoPath . '/demo.docx'),
					);
					$a_model = new Archives();
					if ($a_model->insert($save_data)) {
						$id = $a_model->getLastInsID();
						$this->tableBak('archives', 'archives_version', 'arc_id', 'original_id', $id, 'backup_reasons', '创建');
						jsonOut(1, '创建成功');
					} else {
						jsonOut(0, '创建失败');
					}
				} else {
					jsonOut(0, '创建失败');
				}

				break;
			case 'excel':
				if (empty($cate_id)) {
					jsonOut(0, '请先选择目录后在操作  ');
				}

				if (empty($name)) {
					jsonOut(0, '文件名称部能为空');
				}
				if (is_file($path . $name . '.xlsx')) {
					jsonOut(0, 'xlsx文件已经存在');
				}
				$cp = copy($this->demoPath . '/demo.xlsx', $path . $name . '.xlsx');
				if ($cp) {
					$save_data = array(
						'arc_title' => $title,
						'arc_name' => $name,
						'arc_desc' => $describe,
						'category_id' => $cate_id,
						'create_user_id' => $this->admin_session['id'],
						'create_time' => date('Y-m-d H:i:s'),
						'arc_type' => 'xlsx',
						'update_user_id' => $this->admin_session['id'],
						'update_time' => date('Y-m-d H:i:s'),
						'arc_file_size' => filesize($this->demoPath . '/demo.xlsx'),
					);
					$a_model = new Archives();
					if ($a_model->insert($save_data)) {
						$id = $a_model->getLastInsID();
						$this->tableBak('archives', 'archives_version', 'arc_id', 'original_id', $id, 'backup_reasons', '创建');
						jsonOut(1, '创建成功');
					} else {
						jsonOut(0, '创建失败');
					}
				} else {
					jsonOut(0, '创建失败');
				}
				break;
			case 'txt':
				if (empty($cate_id)) {
					jsonOut(0, '请先选择目录后在操作');
				}

				if (empty($name)) {
					jsonOut(0, '文件名称部能为空');
				}
				if (is_file($path . $name . '.txt')) {
					jsonOut(0, 'Word文件已经存在');
				}
				$cp = copy($this->demoPath . '/demo.txt', $path . $name . '.txt');
				if ($cp) {
					$save_data = array(
						'arc_title' => $title,
						'arc_name' => $name,
						'arc_desc' => $describe,
						'category_id' => $cate_id,
						'create_user_id' => $this->admin_session['id'],
						'create_time' => date('Y-m-d H:i:s'),
						'arc_type' => 'txt',
						'update_user_id' => $this->admin_session['id'],
						'update_time' => date('Y-m-d H:i:s'),
						'arc_file_size' => filesize($this->demoPath . '/demo.txt'),
					);
					$a_model = new Archives();
					if ($a_model->insert($save_data)) {
						$id = $a_model->getLastInsID();
						$this->tableBak('archives', 'archives_version', 'arc_id', 'original_id', $id, 'backup_reasons', '创建');
						jsonOut(1, '创建成功');
					} else {
						jsonOut(0, '创建失败');
					}
				} else {
					jsonOut(0, '创建失败');
				}
				break;
			case 'html':
				if (empty($cate_id)) {
					jsonOut(0, '请先选择目录后在操作');
				}

				if (empty($name)) {
					jsonOut(0, '文件名称部能为空');
				}
				if (is_file($path . $name . '.html')) {
					jsonOut(0, 'Word文件已经存在');
				}
				$cp = copy($this->demoPath . '/demo.html', $path . $name . '.html');
				if ($cp) {
					$save_data = array(
						'arc_title' => $title,
						'arc_name' => $name,
						'arc_desc' => $describe,
						'category_id' => $cate_id,
						'create_user_id' => $this->admin_session['id'],
						'create_time' => date('Y-m-d H:i:s'),
						'arc_type' => 'html',
						'update_user_id' => $this->admin_session['id'],
						'update_time' => date('Y-m-d H:i:s'),
						'arc_file_size' => filesize($this->demoPath . '/demo.html'),
					);
					$a_model = new Archives();
					if ($a_model->insert($save_data)) {
						$id = $a_model->getLastInsID();
						$this->tableBak('archives', 'archives_version', 'arc_id', 'original_id', $id, 'backup_reasons', '创建');
						jsonOut(1, '创建成功');
					} else {
						jsonOut(0, '创建失败');
					}
				} else {
					jsonOut(0, '创建失败');
				}
				break;
			case 'ppt':
				if (empty($cate_id)) {
					jsonOut(0, '请先选择目录后在操作');
				}

				if (empty($name)) {
					jsonOut(0, '文件名称部能为空');
				}
				if (is_file($path . $name . '.pptx')) {
					jsonOut(0, 'Word文件已经存在');
				}
				$cp = copy($this->demoPath . '/demo.pptx', $path . $name . '.pptx');
				if ($cp) {
					$save_data = array(
						'arc_title' => $title,
						'arc_name' => $name,
						'arc_desc' => $describe,
						'category_id' => $cate_id,
						'create_user_id' => $this->admin_session['id'],
						'create_time' => date('Y-m-d H:i:s'),
						'arc_type' => 'pptx',
						'update_user_id' => $this->admin_session['id'],
						'update_time' => date('Y-m-d H:i:s'),
						'arc_file_size' => filesize($this->demoPath . '/demo.pptx'),
					);
					$a_model = new Archives();
					if ($a_model->insert($save_data)) {
						$id = $a_model->getLastInsID();
						$this->tableBak('archives', 'archives_version', 'arc_id', 'original_id', $id, 'backup_reasons', '创建');
						jsonOut(1, '创建成功');
					} else {
						jsonOut(0, '创建失败');
					}
				} else {
					jsonOut(0, '创建失败');
				}
				break;
			}
			jsonOut(0, '创建失败');
		}
	}

	//设置cate_id
	public function setCate_Id() {
		$cate_id = $this->request->post('cate_id', 0);
		// var_dump($cate_id);die;
		session('cate_id', $cate_id);
		jsonOut(1, '设置成功');

	}

	public function setOrg_Id() {
		$org_id = $this->request->post('org_id', 0);
		session('org_id', $org_id);
		jsonOut(1, '设置成功');

	}

	/*数据表备份操作
		                     * @$table1  需要备份的表
		                     * @$table2  备份到的表
		                     * @$pk      主表PK
		                     * @bpk      备份表对应主表的PK
		                     * @rpk      备份特殊字段
		                     * @$remark  备注信息
		                     * @$bid     需要备份的id
	*/
	public function tableBak($table1, $table2, $pk, $bpk, $bid, $rpk, $remark) {
		$table1 = config('database.prefix') . $table1;
		$table2 = config('database.prefix') . $table2;
		$col = Db::query("SHOW COLUMNS FROM `{$table1}`");
		$row = Db::table($table1)->where(array($pk => $bid))->find();
		if (empty($row)) {
			return false;
		}
		$save = array();
		foreach ($col as $k => $v) {
			$save[$v['Field']] = $row[$v['Field']];
		}
		$save[$bpk] = $bid;
		$save[$rpk] = $remark;
		//清掉插入的备份ID 自增ID
		unset($save[$pk]);
		if (Db::table($table2)->insert($save)) {
			return true;
		} else {
			return false;
		}
	}
	//获取文件路径 绝对路径
	public function getFilePath($cate_id, $cate_type = 1, $arc_id = '') {
		$ac_model = new ArchivesCategory();
		$a_model = new Archives();
		if (in_array($cate_id, array('-1', '-2', '-3', '-4'))) {
			$cate_id = 0;
		}
		if (!empty($cate_id)) {
			$p_data = $ac_model->where(array('cate_id' => $cate_id, 'cate_type' => $cate_type))->find();

			$bid = $p_data['create_org_id'];
			if (empty($p_data)) {
				return array('code' => 0, 'msg' => '目录错误');
			}
			if ($p_data['cate_parent_id'] != 0) {
				$p_datas = arrayValueToKey($ac_model->where(array('cate_type' => $cate_type))->select(), 'cate_id');
				$p_path = trim(getAncestors($p_datas, $cate_id, 0), ',');
				$p_path = explode(',', $p_path);
				foreach ($p_path as $k => $v) {
					$p = explode('-', $v);
					$p_path[$k] = $p[1];
				}
				$p_path = array_reverse($p_path, true);
				//$path = $this->folderPath . '/' . $cate_type .'/' . implode('/', $p_path).'/';
				//返回目录为部门ID下而admin应当是主目录
				if (!empty($arc_id)) {
					$a_data = $a_model->find($arc_id);
					$bid = $this->getOrgIdByUid($a_data['create_user_id']);
					$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . implode('/', $p_path) . '/';
					if ($bid == '0') {
						$path = $this->folderPath . '/' . $cate_type . '/' . implode('/', $p_path) . '/';
					}
				} else {
					$bid = $p_data['create_org_id'];
					$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . implode('/', $p_path) . '/';
					if ($bid == '0') {
						$path = $this->folderPath . '/' . $cate_type . '/' . implode('/', $p_path) . '/';
					}
				}
				if ($cate_type == 2) {
					$path = $this->folderPath . '/' . $cate_type . '/' . implode('/', $p_path) . '/';
				}
			} else {
				if (!empty($arc_id)) {
					$a_data = $a_model->find($arc_id);
					$bid = $p_data['create_org_id'];
					$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . $p_data['cate_name'] . '/';
					if ($bid == '0') {
						$path = $this->folderPath . '/' . $cate_type . '/' . $p_data['cate_name'] . '/';
					}
				} else {
					$bid = $p_data['create_org_id'];
					$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . $p_data['cate_name'] . '/';
					if ($bid == '0') {
						$path = $this->folderPath . '/' . $cate_type . '/' . $p_data['cate_name'] . '/';
					}
				}
				if ($cate_type == 2) {
					$path = $this->folderPath . '/' . $cate_type . '/' . $p_data['cate_name'] . '/';
				}

			}
		} else {
			$path = $this->folderPath . '/' . $cate_type . '/';
			if (!empty($arc_id)) {
				$a_data = $a_model->find($arc_id);
				$bid = $this->getOrgIdByUid($a_data['create_user_id']);
				$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/';
				if ($bid == '0') {
					$path = $this->folderPath . '/' . $cate_type . '/';
				}
			} else {
				//此处逻辑有Bug针对 还有未曾修改未曾有arc_id传来的文件
				if ($_SESSION['think']['username'][0]['user_name'] != 'admin') {
					$bid = $this->getOrgIdByUid($_SESSION['think']['username'][0]['user_id']);
					$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/';
				} else {
					$path = $this->folderPath . '/' . $cate_type . '/';
				}
			}

		}
		return array('code' => 1, 'msg' => '成功', 'path' => $path);
	}

	//上传获取路径
	//
	public function getFilePathup($cate_id, $cate_type = 1) {
		$ac_model = new ArchivesCategory();
		$a_model = new Archives();
		if (in_array($cate_id, array('-1', '-2', '-3', '-4'))) {
			$cate_id = 0;
		}
		if (!empty($cate_id)) {
			$p_data = $ac_model->where(array('cate_id' => $cate_id, 'cate_type' => $cate_type))->find();

			$bid = $this->getOrgIdByUid($p_data['create_user_id']);
			if (empty($p_data)) {
				return array('code' => 0, 'msg' => '目录错误');
			}
			if ($p_data['cate_parent_id'] != 0) {
				$p_datas = arrayValueToKey($ac_model->where(array('cate_type' => $cate_type))->select(), 'cate_id');
				$p_path = trim(getAncestors($p_datas, $cate_id, 0), ',');
				$p_path = explode(',', $p_path);
				foreach ($p_path as $k => $v) {
					$p = explode('-', $v);
					$p_path[$k] = $p[1];
				}
				$p_path = array_reverse($p_path, true);
				//$path = $this->folderPath . '/' . $cate_type .'/' . implode('/', $p_path).'/';
				//返回目录为部门ID下而admin应当是主目录
				if (!empty($arc_id)) {
					$a_data = $a_model->find($arc_id);
					$bid = $this->getOrgIdByUid($a_data['create_user_id']);
					$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . implode('/', $p_path) . '/';
					if ($bid == '0') {
						$path = $this->folderPath . '/' . $cate_type . '/' . implode('/', $p_path) . '/';
					}
				} else {
					if ($_SESSION['think']['username'][0]['user_name'] != 'admin') {
						$bid = $this->getOrgIdByUid($p_data['create_org_id']);
						$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . implode('/', $p_path) . '/';
					} else {
						$path = $this->folderPath . '/' . $cate_type . '/' . implode('/', $p_path) . '/';
					}
				}
				if ($cate_type == 2) {
					$path = $this->folderPath . '/' . $cate_type . '/' . implode('/', $p_path) . '/';
				}
			} else {
				if (!empty($arc_id)) {
					$a_data = $a_model->find($arc_id);
					$bid = $this->getOrgIdByUid($a_data['create_user_id']);
					$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . $p_data['cate_name'] . '/';
					if ($bid == '0') {
						$path = $this->folderPath . '/' . $cate_type . '/' . $p_data['cate_name'] . '/';
					}
				} else {
					if ($_SESSION['think']['username'][0]['user_name'] != 'admin') {
						$bid = $this->getOrgIdByUid($p_data['create_org_id']);
						$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/' . $p_data['cate_name'] . '/';
					} else {
						$path = $this->folderPath . '/' . $cate_type . '/' . $p_data['cate_name'] . '/';
					}
				}
				if ($cate_type == 2) {
					$path = $this->folderPath . '/' . $cate_type . '/' . $p_data['cate_name'] . '/';
				}
			}
		} else {
			$path = $this->folderPath . '/' . $cate_type . '/';
			if (!empty($arc_id)) {
				$a_data = $a_model->find($arc_id);
				$bid = $this->getOrgIdByUid($a_data['create_user_id']);
				$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/';
				if ($bid == '0') {
					$path = $this->folderPath . '/' . $cate_type . '/';
				}
			} else {
				//多部门 文件创建  以 部门ID+文件名的形式
				if ($_SESSION['think']['username'][0]['user_name'] != 'admin') {
					$bid = $this->getOrgIdByUid($_SESSION['think']['username'][0]['user_id']);
					$path = $this->folderPath . '/' . $cate_type . '/' . $bid . '/';
				} else {
					$path = $this->folderPath . '/' . $cate_type . '/';
				}
			}

		}
		return array('code' => 1, 'msg' => '成功', 'path' => $path);
	}
	//获取文件路径 相对路径
	public function getFilePathUrl($cate_id, $cate_type = 1, $org_id = '', $arc_id = '') {
		if (in_array($cate_id, array('-1', '-2', '-3', '-4'))) {
			$cate_id = 0;
		}
		$arc_data = $this->a_model->where(array('arc_id' => $arc_id))->where('is_delete', 0)->find();
		$ac_model = new ArchivesCategory();
		if (empty($cate_id)) {
			if (empty($org_id)) {
				if (empty($arc_data['create_org_id'])) {
					$path = 'http://' . $_SERVER['HTTP_HOST'] . '/folder/' . $cate_type . '/';
					if ($_SESSION['think']['username'][0]['user_name'] != 'admin') {
						$bid = $this->getOrgIdByUid($_SESSION['think']['username'][0]['user_id']);
						$path = 'http://' . $_SERVER['HTTP_HOST'] . '/folder/' . $cate_type . '/' . $bid . '/';
					}
				} else {
					$path = 'http://' . $_SERVER['HTTP_HOST'] . '/folder/' . $cate_type . '/' . $arc_data['create_org_id'] . '/';
				}
			} else {
				$path = 'http://' . $_SERVER['HTTP_HOST'] . '/folder/' . $cate_type . '/' . $org_id . '/';
			}
		} else {
			$p_data = $ac_model->where(array('cate_id' => $cate_id, 'cate_type' => $cate_type))->find();
			if (empty($p_data)) {
				return array('code' => 0, 'msg' => '目录错误');
			}
			if ($p_data['cate_parent_id'] != 0) {
				$p_datas = arrayValueToKey($ac_model->where(array('cate_type' => $cate_type))->select(), 'cate_id');
				$p_path = trim(getAncestors($p_datas, $cate_id, 0), ',');
				$p_path = explode(',', $p_path);
				$path_key = '';
				foreach ($p_path as $k => $v) {
					$p = explode('-', $v);
					$p_path[$k] = $p[1];
					$path_key = $p[0];
				}
				$zj_path = $ac_model->where(array('cate_id' => $path_key, 'cate_type' => $cate_type))->find();
				$p_path = array_reverse($p_path, true);
				$path = 'http://' . $_SERVER['HTTP_HOST'] . '/folder/' . $cate_type . '/' . $zj_path['create_org_id'] . '/' . implode('/', $p_path) . '/';
				if ($zj_path['create_org_id'] == '0') {
					$path = 'http://' . $_SERVER['HTTP_HOST'] . '/folder/' . $cate_type . '/' . implode('/', $p_path) . '/';
				}
			} else {
				$path = 'http://' . $_SERVER['HTTP_HOST'] . '/folder/' . $cate_type . '/' . $p_data['create_org_id'] . '/' . $p_data['cate_name'] . '/';
				if ($p_data['create_org_id'] == '0') {
					$path = 'http://' . $_SERVER['HTTP_HOST'] . '/folder/' . $cate_type . '/' . $p_data['cate_name'] . '/';
				}

			}
		}
		return array('code' => 1, 'msg' => '成功', 'path' => $path);
	}
	//获取文件路径 只要数据库路径
	public function getFilePathUrl1($cate_id, $cate_type = 1) {
		if (in_array($cate_id, array('-1', '-2', '-3', '-4'))) {
			$cate_id = 0;
		}
		$ac_model = new ArchivesCategory();
		if (empty($cate_id)) {
			$path = '';
		} else {
			$p_data = $ac_model->where(array('cate_id' => $cate_id, 'cate_type' => $cate_type))->find();
			if (empty($p_data)) {
				return array('code' => 0, 'msg' => '目录错误');
			}
			if ($p_data['cate_parent_id'] != 0) {
				$p_datas = arrayValueToKey($ac_model->where(array('cate_type' => $cate_type))->select(), 'cate_id');
				$p_path = trim(getAncestors($p_datas, $cate_id, 0), ',');
				$p_path = explode(',', $p_path);
				foreach ($p_path as $k => $v) {
					$p = explode('-', $v);
					$p_path[$k] = $p[1];
				}
				$p_path = array_reverse($p_path, true);
				$path = implode('/', $p_path);
			} else {
				$path = $p_data['cate_name'];
			}
		}
		return array('code' => 1, 'msg' => '成功', 'path' => $path);
	}
	//下载文件
	public function toDownload($id, $cate_type = 1) {
		$a_model = new Archives();
		$data = $a_model->getDataByCondition(array('arc_id' => $id));
		$res = $this->acf_model->where(array('arc_id' => $id))->find();
		$res1 = $this->fl_model->where(array('file_id' => $res['file_id']))->find();
		$path = $res1['file_save_path'];
		// $path = $this->getFilePath($data['category_id'], $cate_type, $id);
		$file = $this->rootPath . $path;
		if (file_exists($file)) {
			header("Content-type:application/octet-stream");
			$filename = $data['arc_name'] . '.' . $data['arc_type'];
			header("Content-Disposition:attachment;filename = " . $filename);
			header("Accept-ranges:bytes");
			header("Accept-length:" . filesize($file));
			readfile($file);
		} else {
			echo "<script>alert('文件不存在')</script>";
		}
	}
	//获取文档对应的标签信息
	public function getTagsByArcId($id) {
		$a_model = new Archives();
		$t_model = new TagArchivesRelation();
		$t1_model = new Tag();
		$a_data = $a_model->getDataByCondition(array('arc_id' => $id));
		if (empty($a_data)) {
			return array();
		}
		$t_data = $t_model->getListByCondition(array('arc_id' => $id));
		if ($t_data) {
			foreach ($t_data as $k => $v) {
				$t_data[$k]['tag_info'] = $t1_model->getDataByCondition(array('tag_id' => $v['tag_id']));
			}
			return $t_data;
		} else {
			return array();
		}

	}

	//文件夹修改 删除
	public function folderEdits($cate_type = 1) {
		if ($this->request->instance()->isPost()) {
			$id = $this->request->post('id');
			$delete = $this->request->post('delete');
			$cate_name = $this->request->post('cate_name');
			$cate_desc = $this->request->post('cate_desc');
			if ($delete == 1) {
				//查询下面是否存在文档
				$f_data = $this->a_model->getDataByCondition(array('category_id' => $id));
				$fc_data = $this->ac_model->getDataByCondition(array('cate_parent_id' => $id));
				if ($fc_data) {
					jsonOut(0, '目录下存在目录！请先删除目录后再试');
				}
				if ($f_data) {
					jsonOut(0, '目录下存在文档！请先删除文档后再试');
				} else {
					// $path = $this->getFilePath($id, $cate_type);

					// $rm = @rmdir($path['path']);
					// if ($rm) {
					if ($this->ac_model->updateByCondition(array('cate_id' => $id), array('is_delete' => 1))) {
						//删除文件夹
						session('cate_id', -1);
						jsonOut(1, '删除文件夹成功');
					} else {
						jsonOut(0, '删除文件夹失败');
					}
					// } else {
					// 	jsonOut(0, '文件夹不为空无法删除');
					// }
				}

			}
			if (empty($cate_name)) {
				jsonOut(0, '文件名称不能为空');
			}
			$path = $this->getFilePath($id, $cate_type);
			if ($this->ac_model->updateByCondition(array('cate_id' => $id), array('cate_name' => $cate_name, 'cate_desc' => $cate_desc, 'update_user_id' => $this->admin_session['id'], 'update_time' => date('Y-m-d H:i:s')))) {

				// $new_path = explode('/', trim($path['path'], '/'));
				// array_pop($new_path);
				// $new_path = '/' . implode('/', $new_path) . '/' . $cate_name;
				// rename($path['path'], $new_path);
				jsonOut(1, '编辑成功');
			} else {
				jsonOut(0, '编辑失败');
			}
		}
	}

	//上传文件
	public function uploadFile() {
		$action = $this->request->get('action');
		if ($action == 'tk') {
			$this->saveToken();
		} elseif ($action == 'up') {
			$this->html5Upload();
		}
	}
	//保存token
	public function saveToken() {
		// var_dump(session('cate_id'));die;

		$cate_id = session('cate_id') ? session('cate_id') : 0;
		if (empty($cate_id)) {
			jsonOut(0, '请先选择目录后在操作');
		}

		$get = $this->request->get();
		$cate_type = $get['cate_type'] ? $get['cate_type'] : 1;
		$aaa = strrev($get['name']);
		$bbb = explode(".", $aaa);
		$bbb[0] = strtolower($bbb[0]);
		$ccc = implode(".", $bbb);
		$file['name'] = strrev($ccc); //上传文件名称(原文件名)
		$file['size'] = $get['size']; //上传文件总大小
		$file['token'] = md5(json_encode($file['name'] . $file['size']));
		// $file_path = $this->getFilePath($cate_id, $cate_type);
		// dump($file['token']);
		// dump($this->_tokenPath . '/' . $file['token'] . '.token');
		$path = '/upload/' . date('Ymd') . '/' . rand(0, 9) . '/';
		$eee = explode(".", $file['name']);
		$filetype = end($eee);
		//判断是否存在该令牌信息
		if (!file_exists($this->_tokenPath . '/' . $file['token'] . '.token')) {

			$file['up_size'] = 0; //已上传文件大小
			$pathInfo = pathinfo($file['name']);
			// var_dump($pathInfo);   上传文件名称(原文件名)
			//            $path = iconv("UTF-8", "GBK",$file_path['path']).'/';
			// $path = $file_path['path'];
			//生成文件保存子目录
			//            if(!is_dir(iconv("UTF-8", "GBK",$path))){
			//                mkdir(iconv("UTF-8", "GBK",$path), 0700);
			//            }
			//上传文件保存目录
			$file['new_name'] = $file['token'] . '.' . $pathInfo['extension'];
			$file['filePath'] = $path . time() . '.' . $filetype;
			// var_dump($file['filePath']); 保存目录路径
			$file['modified'] = $get['modified']; //上传文件的修改日期
			//保存令牌信息
			$this->setTokenInfo($file['token'], $file);
		} else {

			//上传了相同文件
			$file['up_size'] = 0;
			$pathInfo = pathinfo($file['name']);
			$name = substr(strrchr($file['name'], '.'), 1);
			// dump($name);die;
			// $res = Db::table('cn_file_log')
			// // ->where('file_new_name', 'like', '%' . $file['token'] . '%')
			//  ->where('file_new_name', $file['token'] . $name)
			// // ->field('file_old_name')
			// // ->order('file_id desc')
			//  ->select();
			$sql = "SELECT

                        *
                    FROM
                        cn_file_log

	                WHERE
	                    file_new_name = '" . $file['token'] . '.' . $name . "'

	                   ";
			$res = Db::query($sql);
			// dump($res);die;
			$i = count($res);
			$name = $res[$i - 1]['file_old_name'];
			$arr = strripos($name, ".");
			$array = substr($name, 0, $arr);
			//判断文件后缀
			$array = $array . '-2';
			$file['name'] = $array . '.' . $pathInfo['extension'];
			//已上传文件大小
			// var_dump($pathInfo);   上传文件名称(原文件名)
			//            $path = iconv("UTF-8", "GBK",$file_path['path']).'/';
			// $path = $file_path['path'];
			//生成文件保存子目录
			//            if(!is_dir(iconv("UTF-8", "GBK",$path))){
			//                mkdir(iconv("UTF-8", "GBK",$path), 0700);
			//            }
			//上传文件保存目录
			$file['new_name'] = $file['token'] . '.' . $pathInfo['extension'];
			$file['filePath'] = $path . time() . '.' . $filetype;
			// var_dump($file['filePath']); 保存目录路径
			$file['modified'] = $get['modified']; //上传文件的修改日期
			//保存令牌信息
			$this->setTokenInfo($file['token'], $file);
		}
		$result['token'] = $file['token'];
		$result['success'] = true;
		$file_log_model = new FileLog();
		$save_data = array(
			'file_old_name' => $file['name'],
			'file_new_name' => $file['new_name'],
			'file_save_path' => $file['filePath'],
			'file_total_size' => $file['size'],
			'file_status' => 2, //上传成功
			'create_user_id' => $this->admin_session['id'],
			'create_time' => date('Y-m-d H:i:s'),
		);
		$code = $file_log_model->insertGetId($save_data);
		// $af_code = array(
		//     '' => ,
		//     '' => $code,
		//     '' => date('Y-m-d H:i:s'),
		//     'is_delete' => 0
		Session::set('file_id', $code);

		// );
		if ($code) {
			// var_dump($result);die;
			echo json_encode($result);exit;
		}
	}
	//H5上传
	public function html5Upload() {
		$type = Session::get('type');
		// return view('index@Index/index');
		$cate_id = session('cate_id') ? session('cate_id') : 0;
		if (empty($cate_id)) {
			jsonOut(0, '请先选择目录后在操作');
		}
		$org_id = $this->getOrgIdByUid($this->admin_session['id']);
		$get = $this->request->get();
		$token = $get['token'];
		$fileInfo = $this->getTokenInfo($token);
		$cate_type = $get['cate_type'] ? $get['cate_type'] : 1;
		$fid = Session::get('file_id');
		if ($fileInfo['size'] > $fileInfo['up_size']) {
			//取得上传内容
			$data = file_get_contents('php://input', 'r');
			if (!empty($data)) {
				//上传内容写入目标文件
				if (!is_dir($this->rootPath . '/upload/' . date('Ymd'))) {
					mkdir($this->rootPath . '/upload/' . date('Ymd'), 0777, true);
					chmod($this->rootPath . '/upload/' . date('Ymd'), 0777);
					for ($i = 0; $i < 10; $i++) {
						mkdir($this->rootPath . '/upload/' . date('Ymd') . '/' . $i, 0777, true);
						chmod($this->rootPath . '/upload/' . date('Ymd') . '/' . $i, 0777);
					}
				}

				$fp = fopen($this->rootPath . $fileInfo['filePath'], 'a');
				flock($fp, LOCK_EX);
				fwrite($fp, $data);
				flock($fp, LOCK_UN);
				fclose($fp);
				//累积增加已上传文件大小
				$fileInfo['up_size'] += strlen($data);
				if ($fileInfo['size'] > $fileInfo['up_size']) {
					$this->setTokenInfo($token, $fileInfo);
				} else {
					$a_model = new Archives();
					//将文件信息保存到对应的数据库里面
					$k = explode('.', $fileInfo['name']);
					$k_num = strrpos($fileInfo['name'], '.');
					$f[0] = substr($fileInfo['name'], 0, $k_num);
					$f[1] = end($k);
					// dump($f);die;
					$fa = $a_model->getDataByCondition(array('arc_name' => $f[0], 'category_id' => $cate_id));

					if (empty($fa)) {
						$save_data = array(
							'arc_title' => $f[0],
							'arc_name' => $f[0],
							'arc_desc' => '',
							'category_id' => $cate_id,
							'create_user_id' => $this->admin_session['id'],
							'create_org_id' => $org_id,
							'create_time' => date('Y-m-d H:i:s'),
							'arc_type' => $f[1],
							'update_user_id' => $this->admin_session['id'],
							'update_time' => date('Y-m-d H:i:s'),
							'arc_file_size' => $fileInfo['size'],
							'mark' => $type,
						);
						// dump($save_data);die;
						$codez = $a_model->insertGetId($save_data);
						Session::set('code', $codez);

						$acf_model = new Archives_file();
						$save_data_af = array(
							'arc_id' => $codez,
							'file_id' => $fid,
							'create_time' => date('Y-m-d H:i:s'),
							'is_delete' => 0,
						);
						$af = $acf_model->insertGetId($save_data_af);

						if ($codez) {
							$id = $a_model->getLastInsID();

							$result['id'] = $id;
							$tree = $this->aa($id);
							$result['tree'] = $tree;
							$this->tableBak('archives', 'archives_version', 'arc_id', 'original_id', $id, 'backup_reasons', '创建');

						}

					}
					$aei_model = new Arc_extend_info();
					$ecode = Session::get('code');
					if ($type == '2' || $type == '3' || $type == '4') {
						//根据type查到扩展字段
						$kuozhan = Db::table('cn_arc_extend')
						// ->where('file_new_name', 'like', '%' . $file['token'] . '%')
							->where('cat_id', $type)
						// ->field('file_old_name')
						// ->order('file_id desc')
							->select();
						// $kuozhan = $this->ae_model->where(array('cat_id' => $type))->select();
						// var_dump($kuozhan);die;
						foreach ($kuozhan as $key => $value) {
							$extend_data = array(
								'extend_id' => $ecode,
								'arc_id' => $value['id'],
								'add_time' => date('Y-m-d H:i:s'),
							);

							$extend_info = $aei_model->insertGetId($extend_data);
						}
					}
					//上传完成后删除令牌信息
					@unlink($this->_tokenPath . $token . '.token');
				}
			}
		}
		$result['start'] = $fileInfo['up_size'];
		$result['success'] = true;
		echo json_encode($result);
		exit;
	}

	public function aa($id) {
		$data = $this->a_model->getDataByCondition(array('arc_id' => $id));

		$params['data'] = $data;
		$ac_data = $this->ac_model->where(array('cate_type' => 1))->select();
		$cate_tree = recursionCate($ac_data, 'cate_id', 0, 'cate_parent_id');
		$tree = createCateTree($cate_tree, 'cate_id', 'cate_parent_id', 'cate_name');
		// var_dump($tree);die;
		return $tree;
	}

	public function removedata($id) {
		// var_dump($id);die;
		if (empty($id)) {
			jsonOut(0, '参数错误');
		}
		$data = $this->a_model->getDataByCondition(array('arc_id' => $id));

		if (empty($data)) {
			jsonOut(0, '文件不存在');
		}
		$params['data'] = $data;
		$ac_data = $this->ac_model->where(array('cate_type' => 1))->select();
		$cate_tree = recursionCate($ac_data, 'cate_id', 0, 'cate_parent_id');
		$tree = createCateTree($cate_tree, 'cate_id', 'cate_parent_id', 'cate_name');
		if (empty($tree)) {
			jsonOut(0, '文件目录错误');
		}
		$params['tree'] = $tree;
		// var_dump($this->request->instance()->isPost());die;
		if ($this->request->instance()->isPost()) {
			$cate_id = $this->request->param('cate_id', '');
			// var_dump($cate_id);die;

			$new_cate = $this->request->param('new_cate', '');
			// var_dump($new_cate);die;
			if (empty($cate_id) || empty($new_cate)) {
				jsonOut(0, '参数错误');
			}
			$path = $this->getFilePath($cate_id);
			$new_path = $this->getFilePath($new_cate);
			$save_data['category_id'] = $new_cate;
			if (is_file($new_path['path'] . '/' . $data['arc_name'] . '.' . $data['arc_type'])) {
				jsonOut(0, '文件已存在');
			}
			$cp = copy($path['path'] . '/' . $data['arc_name'] . '.' . $data['arc_type'], $new_path['path'] . '/' . $data['arc_name'] . '.' . $data['arc_type']);
			if ($cp) {
				if ($this->a_model->updateByCondition(array('arc_id' => $id), array('category_id' => $new_cate))) {
					@unlink($path['path'] . '/' . $data['arc_name'] . '.' . $data['arc_type']);
					$this->tableBak('archives', 'archives_version', 'arc_id', 'original_id', $id, 'backup_reasons', '移动');
					//移动文件记录保存
					$uid = $_SESSION['think']['username'][0]['user_id'];
					$time = date('Y-m-d H:i:s', time());

					//记录用户操作
					$note = [
						'file_id' => $id,
						'file_record' => 6,
						'file_log_desc' => '移动文件',
						'create_user_id' => $uid,
						'create_time' => $time,
					];
					$record = Db::table('cn_file_record')
						->insert($note);
					jsonOut(1, '操作成功');
				} else {
					jsonOut(0, '操作失败');
				}
			} else {
				jsonOut(0, '操作失败');
			}
		}
		// var_dump($params);die;
		return view('index@Prearc/remove', $params);
	}

	/**
	 * 生成文件内容
	 */
	public function setTokenInfo($token, $data) {
		// var_dump($this->_tokenPath .'/'. $token . '.token');exit();
		file_put_contents($this->_tokenPath . '/' . $token . '.token', json_encode($data));
	}
	/**
	 * 获取文件内容
	 */
	public function getTokenInfo($token) {
		$file = $this->_tokenPath . '/' . $token . '.token';
		if (file_exists($file)) {
			return json_decode(file_get_contents($file), true);
		}
		return false;
	}

	//获取用户部门 以及下级部门所有的文件信息
	public function getRoleByUser() {
		$user_id = $_SESSION['think']['username'][0]['user_id'];
		$user_name = $_SESSION['think']['username'][0]['user_name'];

		if ($user_name != 'admin') {
			$oids = $this->getOrgId($user_id);
			$uids = $this->getUserIdByOrdIds($oids);
		} else {
			$uids = 'all';
		}
		return $uids;
	}

	//获取到本部门所有人的uid 在去取文件
	public function getUserIdByOrdIds($ids) {
		$res = Db::table('cn_user_organization_relation')->field('user_id')->where(['org_id' => ['in', $ids]])->select();
		$r = '';
		if ($res) {
			foreach ($res as $k => $v) {
				$r .= $v['user_id'] . ',';
			}
		} else {
			$r = '';
		}
		return trim($r, ',');
	}

	//获取用户当前权限
	public function getUserChara() {
		$uid = $_SESSION['think']['username'][0]['user_id'];
		$res = Db::table('cn_user_character_relation')->field('chara_id')->where(['user_id' => $uid])->find();
		if (empty($res)) {
			return false;
		} else {
			return $res['chara_id'];
		}
	}

	public function getOrgIdByUid($uid) {
		$res = Db::table('cn_user_organization_relation')->field('org_id')->where(['user_id' => $uid])->find();
		if (empty($res)) {
			return false;
		} else {
			return $res['org_id'];
		}
	}

	public function getAllOrgId($bid) {
		$res = Db::table('cn_organization')->where('path', 'like', '%,' . $bid . ',%')->column('org_id');
		array_push($res, $bid);
		return implode(',', $res);
	}

	public function getOrgId($id) {
		// dump($id);die;
		$res = Db::table('cn_user')
			->alias('cu')
			->join('cn_user_organization_relation cuor', 'cuor.user_id = cu.user_id')
			->join('cn_organization co', 'co.org_id = cuor.org_id')
			->where('cu.user_id', $id)
			->where('cu.level', '1')
			->field('co.org_id')
			->find();

		if ($res) {
			$res[0]['org_id'] = $res['org_id'];
			$ares = Db::table('cn_organization')
				->where('path', 'like', '%' . ',' . $res['org_id'] . ',')
				->field('org_id')
				->select();
			$data = array_merge($res, $ares);
			unset($data['org_id']);
			foreach ($data as $key => $value) {
				$data[$key] = $value['org_id'];
			}
			$data = implode(',', $data);
			return $data;
		} else {
			$rres = Db::table('cn_user')
				->alias('cu')
				->join('cn_user_organization_relation cuor', 'cuor.user_id = cu.user_id')
				->join('cn_organization co', 'co.org_id = cuor.org_id')
				->where('cu.user_id', $id)
				->where('cu.level', '0')
				->field('co.org_id')
				->find();
			return $rres['org_id'];
		}

	}

	public function getAuth() {
		//权限过滤
		$mname = request()->controller(); //获取控制器名
		$aname = request()->action(); //获取方法名
		$mname = strtolower($mname);
		$aname = strtolower($aname);

		$auth = Db::table('cn_role')
			->where('mname', $mname)
			->where('aname', $aname)
			->field('priv_id')
			->find();
		$auth = strval($auth['priv_id']);
		// dump($auth);die;
		// 获取权限列表
		$nodelist = Session::get('nodelist');
		// dump($auth);
		// dump($nodelist);die;
		// $nodelist = $_SESSION['think']['username']['nodelist'];
		// dump($auth);
		// dump($nodelist);
		// dump(!in_array($auth,$nodelist));die;
		// 让超级管理员admin拥有所有权限
		if ($_SESSION['think']['username'][0]['user_name'] != 'admin') {
			//     //验证操作权限
			if (empty($nodelist) || !in_array($auth, $nodelist)) {
				$this->error("抱歉！没有操作权限！");
				// alert("抱歉！没有操作权限！");
				exit;
			}
			//common 里面的权限直接跳过
			// if($mname != 'Common') {
			//     if (empty($nodelist[$mname]) || !in_array($aname, $nodelist[$mname])) {
			//         $this->error("抱歉！没有操作权限！");
			//         exit;
			//     }
			// }

		}
	}

}